% Chakram is a subproject of Hexena - Haskell Executable Analyser
% License:			GPL-3
% Maintainer:		Montez Fitzpatrick
% Stability:		Experimental
% Portability:		GHC
% Module:			Hexena.Codec.Parser.SectionHeader

Represents the Section Pages and Table

\begin{code}
module Hexena.Codec.Parser.SectionHeader (parseSecHeader) where

import Data.Binary.Get
import Data.Word
import Data.Bits (shiftR)

import Control.Monad (replicateM)

import Hexena.Data.SectionHeader (SectionHeader(..), Section(..))

-- | Parsing Section Header
--   n := is the number of Sections that need to be parsed.
parseSecHeader :: Int -> Get SectionHeader
parseSecHeader n = parseSections n >>= \sects -> return $ SectionHeader sects

-- | Parsing Sections
--   n := is the number of Sections that need to be parsed.
parseSections :: Int -> Get [Section]
parseSections n = replicateM n parseSection

-- | Parsing Section 
parseSection :: Get Section
parseSection = do
  w_name <- getWord64le -- Name
  w_virtSz <- getWord32le -- Virtual Size
  w_virtAr <- getWord32le -- Virtual Address
  w_szRwDa <- getWord32le -- Size of Raw Data
  w_ptRwDa <- getWord32le -- Pointer to Raw Data
  w_ptReloc <- getWord32le -- Pointer to Relocations
  w_ptLnNum <- getWord32le -- Pointer to Line Numbers
  w_nmReloc <- getWord16le -- Number of Relocations
  w_nmLnNum <- getWord16le -- Number of Line Numbers
  w_char <- getWord32le -- Characteristics

  return $ Section w_name w_virtSz w_virtAr w_szRwDa w_ptRwDa w_ptReloc w_ptLnNum w_nmReloc w_nmLnNum w_char

-- | Parsing Section 
parseSection' :: Int -> Get [Section]
parseSection' n = replicateM n $ do
  w_name <- getWord64le -- Name
  w_virtSz <- getWord32le -- Virtual Size
  w_virtAr <- getWord32le -- Virtual Address
  w_szRwDa <- getWord32le -- Size of Raw Data
  w_ptRwDa <- getWord32le -- Pointer to Raw Data
  w_ptReloc <- getWord32le -- Pointer to Relocations
  w_ptLnNum <- getWord32le -- Pointer to Line Numbers
  w_nmReloc <- getWord16le -- Number of Relocations
  w_nmLnNum <- getWord16le -- Number of Line Numbers
  w_char <- getWord32le -- Characteristics

  return $ Section w_name w_virtSz w_virtAr w_szRwDa w_ptRwDa w_ptReloc w_ptLnNum w_nmReloc w_nmLnNum w_char

-- | unpack name into ByteString
unpack64 :: Word64 -> [Word8]
unpack64 x = map (fromIntegral . (shiftR x)) [0,8..56]
\end{code}
